package com.yh.server;

import javax.servlet.ServletException;
import javax.swing.SwingUtilities;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

public class EmbededTomcat {
	
	private static Tomcat tomcat = null;
	private int port = 9999;
	
	public EmbededTomcat ( int port ) {
		super ( );
		this.port = port;
	}
	
	public static void main ( String [ ] args ) {
		// run ( );
		// Properties aaa=System.getProperties ( ) ;
		// for( Object s: aaa.keySet ( )){
		// System.out.println(s+"==="+aaa.getProperty ( s.toString ( ) ));
		// }
	}
	
	public void run ( ) {
		
		if ( null != tomcat && tomcat.getServer ( ).getState ( ).isAvailable ( ) ) return;
		//
		new Thread ( ( new Runnable ( ) {
			@Override
			public void run ( ) {
				try {
					start ( );
				} catch ( Exception e ) {
					e.printStackTrace ( );
				}
			}
		} ) ).start ( );
	}
	
	private void start ( ) throws ServletException , LifecycleException {
		tomcat = new Tomcat ( );
		tomcat.setBaseDir ( System.getProperty ( "java.io.tmpdir" ) );
		tomcat.addWebapp ( "" , System.getProperty ( "user.dir" ) + "/web" );
		tomcat.getConnector ( ).setPort ( port );
		tomcat.getConnector ( ).setURIEncoding ( "UTF-8" );
		// /
		tomcat.start ( );
		tomcat.getServer ( ).await ( );
	}
	
}
